package com.sxt.service.impl;

import com.sxt.common.CodeMsg;
import com.sxt.common.Constant;
import com.sxt.common.PageInfo;
import com.sxt.common.Result;
import com.sxt.dao.UserDao;
import com.sxt.pojo.User;
import com.sxt.service.IUserService;

import java.util.List;
import java.util.Map;

/**
 * @Description: 业务实现类
 * @author: Mr.T
 * @date 2020-11-03 11:16
 */
public class UserServiceImpl implements IUserService {

    UserDao userDao = new UserDao();


    @Override
    public Result login(String username, String password) {
        User user = userDao.selectUser(username, password);
        if (user == null){
            return  new Result(CodeMsg.USER_LOGIN_ERROR);
        }
        //判断用户状态
        if (user.getDeleted().equals(Constant.USER_DELETE_INVALID)){
            return new Result(CodeMsg.USER_IS_DELETED_ERROR);
        }
        return new Result(user);
    }

    @Override
    public Result queryPage(Map<String, String> params, String page, String limit) {
        // 前端需要数据格式
        /**
         *   code  业务码
         *
         *   msg    业务消息
         *
         *   data   符合条件的数据
         *
         *   count  符合条件的总数据条数
         *
         *
         */
        PageInfo<User> pageInfo =  userDao.selectPage(params,page,limit);

        return new Result(pageInfo);
    }

    @Override
    public Result delete(String id) {
        userDao.updateState(id,Constant.USER_DELETE_INVALID);
        return new Result();
    }


    @Override
    public Result reset(String id) {
        userDao.updatePassword(id,Constant.DEFAULT_PASSWORD);
        return  new Result();
    }


    @Override
    public Result add(String username, String password, String realname, String role) {
        //进行业务数据校验
        //校验用户名是否存在
        User user = userDao.selectUserByUsername(username);
        if (user != null){
            return  new Result(CodeMsg.USER_NAME_EXIST_ERROR);
        }
        userDao.insert(username,password,realname,role);
        return new Result();
    }

    @Override
    public Result queryAllSalesman() {
        List<User> users = userDao.selectUsersByRole(Constant.USER_ROLE_SALESMAN,Constant.USER_DELETE_VALID);
        return new Result(users);
    }


    @Override
    public Result updatePassword(Integer userId, String newPassword) {
        userDao.updatePassword(userId.toString(),newPassword);
        return new Result();
    }

    @Override
    public Result updateImg(Integer id, String url) {
        userDao.updateImg(id,url);
        return new Result(url);
    }
}
